package com.sykj.manage.web;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sykj.manage.service.BisNurseProjectsService;
import com.sykj.manage.model.BisNurseProject;
import com.sykj.util.MYSConstant;
import com.sykj.util.ManageBody;
import com.sykj.util.PageUtil;

@Controller
@RequestMapping("/bnp")
public class BisNurseProjectsController {

	@Autowired
	BisNurseProjectsService bisNurseProjectsService;

	@RequestMapping("/list")
	@ResponseBody
	public ManageBody findAll(BisNurseProject bisNurseProject,Integer offset,Integer pageSize){
		PageHelper.startPage(offset==null?1:PageUtil.getPageNum(offset, pageSize), pageSize==null?10:pageSize, true);
		List<BisNurseProject> findAll = bisNurseProjectsService.findAll(bisNurseProject);
		PageInfo<BisNurseProject> pageInfo = new PageInfo<BisNurseProject>(findAll);
		return ManageBody.getData((int)pageInfo.getTotal(), pageInfo.getList(), "");
	}
	
	@RequestMapping("/deleteId/{project_id}")
	@ResponseBody
	public ManageBody deleteId(@PathVariable("project_id")String project_id){
		int deleteId = bisNurseProjectsService.deleteId(project_id);
		if (deleteId>0) {
			System.out.println("删除了"+deleteId+"数据，Id是："+project_id);
			return ManageBody.getData(1, deleteId, "");
		} else {
			return ManageBody.getData(1, deleteId, "");
		}
	}
	
	@RequestMapping("/addProjects")
	public String add(BisNurseProject bisNurseProject,@RequestParam(value="file",required=false) MultipartFile[] file,HttpServletRequest request)throws IOException{
		int count = 1;
		for (MultipartFile mf : file) {
			if (!mf.isEmpty()) {
				//使用UUID给图片重命名，并去掉四个“-”
				String name = UUID.randomUUID().toString().replace("-", "");
				//获取文件的扩展名
				String ext = FilenameUtils.getExtension(mf.getOriginalFilename());
				//设置图片上传路径
				String url = request.getSession().getServletContext().getRealPath("/");
				System.out.println(url);
				//把图片上传路径常量调过来
				String fullPath = MYSConstant.UPLOAD_MANAGE_PROJECT + name + "." + ext;
				File file1 = new File(url+fullPath);
				if (!file1.exists()) {
					file1.createNewFile();
				}
				//以绝对路径保存重命名后的图片
				mf.transferTo(file1);
				//把图片存储路径保存到数据库
				if (count==1) {
					bisNurseProject.setCover_photo(fullPath);
				}else if(count==2){
					bisNurseProject.setCover_big_photo(fullPath);
				}
			}
			count++;
		}
		
		bisNurseProject.setModify_time(new Date());
		bisNurseProject.setCreate_time(new Date());
		int addProjects = bisNurseProjectsService.addProjects(bisNurseProject);
		if (addProjects>0) {
			System.out.println("=========================================="+addProjects);
		}
		return "redirect:/manage/myloginfo.html";
	}
	
	//id查询
		@RequestMapping("/findByProjectId/{project_id}")
		@ResponseBody
		public ManageBody Info(@PathVariable("project_id") String project_id ){
			//根据id获取所选对象数据
			BisNurseProject findByProjectId = bisNurseProjectsService.findByProjectId(project_id);
			System.out.println("====="+findByProjectId);
			return ManageBody.getData(1, findByProjectId, "");
		}
		
		//护理项目查看详情
				@RequestMapping("getProlistBy")
				@ResponseBody
				public ManageBody getProlistBy(@PathVariable("project_id") String project_id ){
					//根据id获取所选对象数据
					BisNurseProject findByProjectId = bisNurseProjectsService.findByProjectId(project_id);
					System.out.println("====="+findByProjectId);
					return ManageBody.getData(1, findByProjectId, "");
				}
		
		//id查询详情
				@RequestMapping("/findByProjectXQ/{project_id}")
				@ResponseBody
				public ManageBody XQ(@PathVariable("project_id") String project_id ){
					//根据id获取所选对象数据
					BisNurseProject findByProjectXQ = bisNurseProjectsService.findByProjectXQ(project_id);
					System.out.println("====="+findByProjectXQ);
					return ManageBody.getData(1, findByProjectXQ, "");
				}
				
				//根据ID查询某一列数据
				@RequestMapping("/findById")
				@ResponseBody
				public Object findById(String ida){
					BisNurseProject findById = bisNurseProjectsService.findByProjectId(ida);
					return findById;
				}
		
		
		//修改
		@RequestMapping("/updateProject")
		public String updateProject(BisNurseProject bisNurseProject,@RequestParam(value="file",required=false) MultipartFile[] file,HttpServletRequest request)throws IOException{
			int count=1;
		    for (MultipartFile mf : file) {
		        if(!mf.isEmpty()){
		            // 使用UUID给图片重命名，并去掉四个“-”
		            String name = UUID.randomUUID().toString().replaceAll("-", "");
		            // 获取文件的扩展名
		            String ext = FilenameUtils.getExtension(mf
		            .getOriginalFilename());  
		            // 设置图片上传路径
		            String url = request.getSession().getServletContext().getRealPath("/");
		            System.out.println(url);
		            //把图片上传路径的常量调用过来
		            String fullPath =  MYSConstant.UPLOAD_MANAGE_PROJECT + name + "." + ext;
		            File file1 = new File(url + fullPath);
		            if (!file1.exists()) {
		            	file1.createNewFile();
		            }
		            // 以绝对路径保存重名命后的图片
		            mf.transferTo(file1);
		            // 把图片存储路径保存到数据库
		            if(count==1){
		            	bisNurseProject.setCover_photo(fullPath);
		            }else if(count==2){
		            	bisNurseProject.setCover_big_photo(fullPath);
		            }
		        }  
		        count++;
		    }
			
		    bisNurseProject.setModify_time(new Date());
			int updateProject = bisNurseProjectsService.updateProject(bisNurseProject);
			if (updateProject>0) {
				System.out.println("====================修改了"+updateProject);
			}
			return "redirect:/manage/myloginfo.html";
		}
		
		// 富文本上传图片
		@RequestMapping("/fileUpload")
		@ResponseBody
		public Map<String, Object> fileUpload(HttpServletRequest req) throws Exception, IOException {
			Map<String, Object> map = new HashMap<>();
			CommonsMultipartResolver resolver = new CommonsMultipartResolver(req.getSession().getServletContext());
			if (resolver.isMultipart(req)) {
				MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
				Iterator<String> fileNameIter = mreq.getFileNames();
				while (fileNameIter.hasNext()) {
					MultipartFile file = mreq.getFile(fileNameIter.next());
					if (file != null) {
						String fileName = file.getOriginalFilename();

						String fileBaseName = fileName.substring(0, fileName.lastIndexOf("."));

						String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

						SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");

						String newFileName = df.format(new Date());

						String fileNames = newFileName + new Random().nextInt(1000) + "." + fileExt;

						String filePath = req.getSession().getServletContext().getRealPath("/") + MYSConstant.UPLOAD_MANAGE_PROJECT
								+ fileNames;

						File localFile = new File(filePath);
						if (!localFile.exists()) {
							localFile.mkdir();
						}
						file.transferTo(localFile);
						fileNames = MYSConstant.BASE_URL + MYSConstant.UPLOAD_MANAGE_PROJECT + fileNames;
						map.put("name", fileBaseName);
						map.put("path", fileNames);
						return map;
					}
				}
			}
			return null;
		}
}
